package com.cuit.provider;

import com.cuit.bean.CurrentServiceState;
import com.cuit.config.RpcServiceConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class CurrentStateTimer {

    private final Map<String, CurrentServiceState> currentServiceStateMap;
    //非核心业务
    private final Map<String, CurrentServiceState> notCoreCurrentServiceStateMap;

    public void put(RpcServiceConfig rpcServiceConfig){
        CurrentServiceState currentServiceState = new CurrentServiceState();
        currentServiceState.getVip().set(rpcServiceConfig.getVip());
        this.put(rpcServiceConfig.getRpcServiceName(), currentServiceState);
        if (!rpcServiceConfig.getVip()){
            notCoreCurrentServiceStateMap.put(rpcServiceConfig.getRpcServiceName(), currentServiceState);
        }
    }

    public void put(String serviceName, CurrentServiceState currentServiceState){
        currentServiceStateMap.put(serviceName, currentServiceState);
    }

    public CurrentServiceState get(String serviceName){
        return currentServiceStateMap.get(serviceName);
    }

    public CurrentServiceState getNotCore(String serviceName){
        return notCoreCurrentServiceStateMap.get(serviceName);
    }

    public CurrentStateTimer() {
        this.notCoreCurrentServiceStateMap = new ConcurrentHashMap<>();
        this.currentServiceStateMap = new ConcurrentHashMap<>();

        ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
        scheduledExecutorService.scheduleAtFixedRate(()->{
            Iterator<Map.Entry<String, CurrentServiceState>> iterator = notCoreCurrentServiceStateMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, CurrentServiceState> entry = iterator.next();
                CurrentServiceState currentServiceState = entry.getValue();
                Double successRate = currentServiceState.calcServiceSuccessRate();
                log.info("服务[{}]的调用成功率:{}",entry.getKey(), successRate);
                if (successRate < 0.8 && !currentServiceState.getHasDegrade().get()){
                    log.info("服务[{}]启用降级处理", entry.getKey());
                    currentServiceState.getHasDegrade().set(true);
                }
            }
        }, 30, 60, TimeUnit.SECONDS);
    }
}
